import { Component, OnInit, Input, OnDestroy, Inject } from '@angular/core';
import { ILayoutService, LAYOUT_SERVICE } from '../inerface/layout-service.interface';
import { ComponentInfoModel } from '../model/component-info.model';
import { ILayoutSettingConfig } from '../model/layout.setting.config';
import { ContextService } from "wit-core";
import { TranslateService } from "ng2-translate";
import { Subscription } from 'rxjs/subscription';
import { Observable } from 'rxjs/observable';

@Component({
    selector: 'elite-layout-setting',
    templateUrl: './layout.setting.component.html',
    styleUrls: ['./layout.setting.component.scss']
})
export class EliteLayoutSettingComponent implements OnInit, OnDestroy {
    @Input() config: ILayoutSettingConfig;
    componentInfos: ComponentInfoModel[];
    editingCmpInfo: any = {};
    private _selectedComponentInfo: ComponentInfoModel;

    constructor( @Inject(LAYOUT_SERVICE) private _layoutSev: ILayoutService, private translate: TranslateService) {
        this.componentInfos = [];
    }

    get selectedComponentInfo() {
        return this._selectedComponentInfo;
    }

    set selectedComponentInfo(v: ComponentInfoModel) {
        if (this._selectedComponentInfo == v)
            return;

        this._selectedComponentInfo = v;
        this.changelayout();
    }

    ngOnInit() {
        this.initComponentInfos();
    }


    private initComponentInfos() {
        this.getComponentInfoWithDefaults()
            .toArray()
            .subscribe(arr => {
                this.componentInfos = arr;
                this.setDefaultComponentInfo(this.componentInfos);
            });
    }

    public getComponentInfoWithDefaults(): Observable<ComponentInfoModel> {
        let cmpName: string = null;
        if (this.isLayoutConfigaVailable()) {
            cmpName = this.config.settingProvider.provideCmpType();
        }
        return this._layoutSev.getUserComponentWithDefaults(ContextService.CurrentContext.user, cmpName);
    }

    saveLayout() {
        if (!this.isLayoutConfigaVailable())
            return;

        if (!this.selectedComponentInfo) {
            let newComponentInfo = this.createLayoutComponent();

            if (!newComponentInfo)
                return;

            this.componentInfos.push(newComponentInfo);
            this.setDefaultComponentInfo(this.componentInfos);
        }
        else {
            this._selectedComponentInfo.data = this.config.settingProvider.save();
            this._layoutSev.insertLayoutComponent(this._selectedComponentInfo)
                .then(function (e) {
                    console.log(e);
                });
        }
    }

    removeLayout() {
        if (!this.selectedComponentInfo)
            return;

        return this._layoutSev.deleteLayoutComponent(this.selectedComponentInfo.componentKey)
            .then(r => {
                let removedItemIndex = this.componentInfos.findIndex(ls => ls.componentKey === this.selectedComponentInfo.componentKey);
                this.componentInfos.splice(removedItemIndex, 1);
                this.setDefaultComponentInfo(this.componentInfos);
            },
            error => {
                console.log(error)
            });
    }

    saveLayoutAs() {
        this.config.editorVisible = true;
        this.editingCmpInfo = {
            name: ''
        };
    }

    changelayout(): void {
        if (!this.isLayoutConfigaVailable())
            return;

        this.config.settingProvider.restore(this.selectedComponentInfo);
    }

    saveLayoutSettingAs(event: any) {
        let cmpName = this.editingCmpInfo.name;

        if (!cmpName)
            return;

        let newComponentInfo = this.createLayoutComponent(cmpName);

        if (!newComponentInfo)
            return;

        this.componentInfos.push(newComponentInfo);
        this.setDefaultComponentInfo(this.componentInfos);
        this.config.editorVisible = false;
    }

    cancelSaveLayoutSetting() {
        this.config.editorVisible = false;
    }

    ngOnDestroy(): void {
        this.config = null;
    }

    private setDefaultComponentInfo(arr: ComponentInfoModel[]) {
        if (!arr || arr.length <= 0) {
            this.selectedComponentInfo = null;
            return;
        }

        let defaultCmpInfo = arr.find(a => a.isDefault) || arr[0];
        if (defaultCmpInfo) {
            this.selectedComponentInfo = defaultCmpInfo;
        }
    }

    private createLayoutComponent(cmpName?: string): ComponentInfoModel {
        if (!this.isLayoutConfigaVailable())
            return null;

        let newComponentInfo = this._layoutSev.createEntity();
        newComponentInfo.componentName = cmpName || this.config.settingProvider.provideCmpName();
        newComponentInfo.componentType = this.config.settingProvider.provideCmpType();
        newComponentInfo.data = this.config.settingProvider.save();

        this._layoutSev.insertLayoutComponent(newComponentInfo)
            .then(function (e) {
                console.log(e);
            });

        return newComponentInfo;
    }

    private isLayoutConfigaVailable() {
        return this.config
            && this.config.settingProvider
            && this.config.settingProvider.restore
            && this.config.settingProvider.save;
    }
}